package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    private  final CheckInMapper checkInMapper;
    private  final ElderMapper elderMapper;
    private  final BedMapper bedMapper;
    private  final CheckInConfigMapper checkInConfigMapper;
    private  final ContractMapper contractMapper;

    private static final Integer BED_STATUS_USED = 1 ;
    private static final Integer ELDER_STATUS_LIVEING = 0 ;
    private static final Integer CONTECT_STATUS_INEFFECT = 1 ;
    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    @Transactional
    public CheckInDetailVo selectCheckInById(Long id)
    {
        //查询checkin内容
        CheckIn checkIn = checkInMapper.selectById(id);

        //查询elder内容
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        //查询家庭内容
        ElderFamilyVo elderFamilyVo = new ElderFamilyVo();
        String family = checkIn.getRemark();
        List<ElderFamilyVo> familyList = JSONUtil.toList(family, ElderFamilyVo.class);
        //查询入住配置内容
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        //查询合同内容
        LambdaQueryWrapper<Contract> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(queryWrapper2);

        //封装所有数据
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(familyList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param applyDto 入住
     * @return 结果
     */
    @Override
    @Transactional
    public void insertCheckIn(CheckInApplyDto applyDto)
    {
       //先查询老人是否已经入住 根据身份证查询
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,applyDto.getCheckInElderDto().getIdCardNo());

        List<Elder> elders = elderMapper.selectList(queryWrapper);
        if (elders!=null && elders.size()>0){
            throw new RuntimeException("该老人已入住");
        }
        //修改床位入住状态
        log.info("修改床位入住状态");
        Bed bed = bedMapper.selectBedById(applyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(BED_STATUS_USED);
        bedMapper.updateById(bed);
        log.info("床位入住状态修改为已入住");

        //新增老人表
        Elder elder = insertEleder(applyDto, bed);

        //新增入住信息+家属信息/
        CheckIn checkIn = insetCheckIn(elder,bed,applyDto.getElderFamilyDtoList(),applyDto.getCheckInConfigDto());

        //新增入住配置
        insertCheckConfig(checkIn,applyDto.getCheckInConfigDto());

        //新增合同表
        insetContract(elder,applyDto.getCheckInContractDto(),checkIn);
    }

    /**
     * 新增合同
     * @param elder
     * @param checkInContractDto
     * @param checkIn
     */
    private void insetContract(Elder elder, CheckInContractDto checkInContractDto, CheckIn checkIn) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkIn.getStartDate());
        contract.setEndDate(checkIn.getEndDate());
        // 设置合同编号，可以使用时间戳或其他唯一标识
        contract.setContractNumber("HT" + System.currentTimeMillis());
        if (checkIn.getStartDate().isBefore(LocalDateTime.now())){
            contract.setStatus(CONTECT_STATUS_INEFFECT);
        }
        contractMapper.insert(contract);

    }

    /**
     * 新增入住配置
     * @param checkIn
     * @param checkInConfigDto
     */
    private void insertCheckConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param bed
     * @param elderFamilyDtoList
     * @param checkInConfigDto
     * @return
     */
    private CheckIn insetCheckIn(Elder elder, Bed bed, List<ElderFamilyDto> elderFamilyDtoList, CheckInConfigDto checkInConfigDto) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(elder,checkIn);
        BeanUtils.copyProperties(checkInConfigDto,checkIn);
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        // 显式设置elderName字段
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkInMapper.insert(checkIn);

        return checkIn;
    }

    /**
     * 新增老人表信息
     * @param applyDto
     * @param bed
     */
    private Elder insertEleder(CheckInApplyDto applyDto,Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(applyDto.getCheckInElderDto(),elder);
        elder.setStatus(ELDER_STATUS_LIVEING);
        elder.setBedId(applyDto.getCheckInConfigDto().getBedId());
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elderMapper.insert(elder);
        return elder;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }

}
